import { createApp } from 'vue'
import Toast from '@/components/Toast.vue'

// Toast管理类
class ToastManager {
  constructor() {
    this.toasts = []
  }

  // 显示Toast
  show(options) {
    const {
      type = 'success',
      title = '',
      message = '',
      duration = 3000
    } = options

    // 创建Toast容器
    const container = document.createElement('div')
    document.body.appendChild(container)

    // 创建Toast实例
    const app = createApp(Toast, {
      type,
      title,
      message,
      duration
    })

    const instance = app.mount(container)

    // 保存引用
    this.toasts.push({
      app,
      container,
      instance
    })

    // 自动清理
    if (duration > 0) {
      setTimeout(() => {
        this.remove(instance)
      }, duration)
    }

    return instance
  }

  // 移除Toast
  remove(instance) {
    const index = this.toasts.findIndex(toast => toast.instance === instance)
    if (index > -1) {
      const { app, container } = this.toasts[index]
      app.unmount()
      document.body.removeChild(container)
      this.toasts.splice(index, 1)
    }
  }

  // 清空所有Toast
  clear() {
    this.toasts.forEach(({ app, container }) => {
      app.unmount()
      document.body.removeChild(container)
    })
    this.toasts = []
  }

  // 快捷方法
  success(title, message, duration) {
    return this.show({ type: 'success', title, message, duration })
  }

  error(title, message, duration) {
    return this.show({ type: 'error', title, message, duration })
  }

  warning(title, message, duration) {
    return this.show({ type: 'warning', title, message, duration })
  }

  info(title, message, duration) {
    return this.show({ type: 'info', title, message, duration })
  }
}

// 创建全局实例
const toast = new ToastManager()

export default toast






